package netp;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

public class EchoServer {

    // port number
    private final int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        final int port = 2222;

        new EchoServer(port).start();
    }

    // call the server
    public void start() throws Exception {

        // create `EventLoop` group
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            ServerBootstrap btsp = new ServerBootstrap();

            // create `ServerBootstrap`
            btsp.group(group)

                // use `Channel` by `nio`
                .channel(NioServerSocketChannel.class)

                // set socket address port
                .localAddress(new InetSocketAddress(this.port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {

                        // add EchoServerHandler to `ChannelPipeline` of `Channel`
                        ch.pipeline().addLast(new EchoServerHandler());
                    }
                });

            // bind the server and use `sync` to wait for its closing
            ChannelFuture f = btsp.bind().sync();
            System.out.println(EchoServer.class.getName() + " started and listen on " + f.channel().localAddress());

            // close channel and block util they are turned down
            f.channel().closeFuture().sync();
        } finally {

            // turn down `EventLoopGroup` and release all the resources
            group.shutdownGracefully().sync();
        }
    }
}